#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/8/27 14:38
# @File           : crud
# @IDE            : PyCharm
# @desc           : 辅料收集需求
from datetime import datetime

from sqlalchemy.ext.asyncio import AsyncSession

from core.crud import DalBase
from core.exception import CustomException
from . import models, schemas


class NeedPlanDal(DalBase):
    def __init__(self, db: AsyncSession):
        super(NeedPlanDal, self).__init__()
        self.db = db
        self.model = models.DCNeedPlan
        self.schema = schemas.NeedPlanSimpleOut

    async def drop_plan(self, data_id):
        plan = await self.get_data(data_id=data_id)
        if plan.status != "收集中":
            raise CustomException("该状态下计划不允许废弃")
        plan.status = '已废弃'
        await self.db.flush()
        return plan

    async def call_plan(self, data_id):
        plan = await self.get_data(data_id=data_id)
        if plan.status != "收集中":
            raise CustomException("该状态下，不允许下发配送任务")
        if not plan.items:
            raise CustomException("需求量为0，不允许下发配送任务")
        # todo: 集成物料配送接口
        plan.status = '已下发'
        plan.transport_id = "M0001"
        plan.transport_datetime = datetime.now()
        await self.db.flush()
        return plan
